import { nextTick } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
export const base = import.meta.env.DEV ? '/' : '/decision-engine';
// import { ADMIN_ROLECODE } from '@/constants/config';

const router = createRouter({
  history: createWebHistory(base),
  scrollBehavior(to, from) {
    if (to.name === from.name) return;

    nextTick(() => {
      const wrap = document.querySelector('.main-container');
      if (wrap) wrap.scrollTop = 0;
    });
  },
  routes: [
    {
      path: '/403',
      component: () => import('@/views/error/403/index.vue'),
      name: '403'
    },
    {
      path: '/404',
      component: () => import('@/views/error/404/index.vue'),
      name: '404'
    },
    {
      path: '/:pathMatch(.*)',
      redirect: '/404'
    },
    {
      path: '/',
      name: 'Layout',
      component: () => import('@/layout/index.vue'),
      redirect: { name: 'Home' },
      children: [
        {
          path: '/home',
          component: () => import('@/views/home-page'),
          name: 'Home',
          meta: {
            title: '首页'
          }
        },
        {
          path: '/flow',
          component: () => import('@/views/decision-flow'),
          name: 'DecisionFlow',
          meta: {
            title: '决策'
          }
        },
        {
          path: '/data-source',
          component: () => import('@/views/data-source'),
          name: 'DataSource',
          meta: {
            title: '资源中心',
            icon: 'mci-icon-dashboard'
          }
        },
        {
          path: '/doc-create',
          component: () => import('@/views/doc-create'),
          name: 'DocCreate',
          meta: {
            title: '生成API文档',
            hidden: true
          }
        },
        {
          path: '/open-interface',
          component: () => import('@/views/open-interface'),
          name: 'OpenInterface',
          meta: {
            title: '开放接口',
            hidden: true
          }
        },
        {
          path: '/timed-execution',
          component: () => import('@/views/timed-execution'),
          name: 'TimedExecution',
          meta: {
            title: '定时任务',
            hidden: true
          }
        }
      ]
    }
  ]
});
router.beforeEach(async (to, from, next) => {
  // 删除kc query参数
  if (to.query.session_state) {
    const query = Object.assign({}, to.query);
    delete query['session_state'];
    delete query['state'];
    delete query['code'];
    return next({ name: to.name?.toString(), params: to.params, query });
  }
  // 管理员可查看开放接口
  // if (to.name === 'OpenInterface'){
  //   if (appStore?.mcisaas?.roles?.some(item => Number(item.roleCode) === ADMIN_ROLECODE)) {
  //     return next();
  //   }else{
  //     return next({ name: '403', replace: true });
  //   }
  // }
  return next();
});

export const getMenus = () => {
  return router.getRoutes().find((item) => item.name === 'Layout')?.children || [];
};

export default router;
